<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addAEditRole('add')"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['dbbottom', i1 === 0 ? 'dbTop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="rolesClose(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="item2 in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="rolesClose(scope.row, item2.id)"
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"> </i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="rolesClose(scope.row, item3.id)"
                    >
                      {{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="edit"
              @click="addAEditRole('edit', scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="delete"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="setting"
              @click="showSetRight(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="rightDialogVisible"
      width="50%"
      @close="rightDialogClose"
    >
      <el-tree
        :data="rightList"
        :props="rightProps"
        ref="rightRef"
        :default-checked-keys="defKeys"
        node-key="id"
        default-expand-all
        show-checkbox
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRight">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="addAEditDialogTitle"
      :visible.sync="addAEditDialogVisible"
      width="50%"
      @close="addAEditDialogClose"
    >
      <el-form
        :model="addAEditRoleForm"
        :rules="addAEditRoleFormRules"
        ref="addAEditRoleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addAEditRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addAEditRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAEditDialogclick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      roleList: [],
      rightDialogVisible: false,
      rightList: [],
      rightProps: {
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: '',
      addAEditTitle: '',
      editRoleId: '',
      addAEditDialogVisible: false,
      addAEditRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addAEditRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败!')
      console.log(res)
      this.roleList = res.data
    },
    async rolesClose (row, rightId) {
      const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除角色权限失败！')
      this.$message.success('删除角色权限成功！')
      row.children = res.data
    },
    async showSetRight (row) {
      this.roleId = row.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败！')
      this.rightList = res.data
      console.log(this.rightList)
      this.defKeysFn(row, this.defKeys)
      this.rightDialogVisible = true
    },
    defKeysFn (value, arr) {
      if (!value.children) {
        return arr.push(value.id)
      }
      value.children.forEach(item => {
        this.defKeysFn(item, arr)
      })
    },
    async setRight () {
      const keys = [
        ...this.$refs.rightRef.getHalfCheckedKeys(), ...this.$refs.rightRef.getCheckedKeys()
      ]
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keys.join(',') })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取角色授权失败！')
      this.$message.success('获取角色授权成功！')
      this.rightDialogVisible = false
      this.getRoleList()
    },
    rightDialogClose () {
      this.defKeys = []
    },
    async addAEditRole (type, id) {
      this.addAEditTitle = type
      this.editRoleId = id
      this.addAEditRoleForm.roleName = ''
      this.addAEditRoleForm.roleDesc = ''
      if (type === 'edit') {
        const { data: res } = await this.$http.get('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('查询角色列表失败！')
        this.addAEditRoleForm = res.data
      }
      this.addAEditDialogVisible = true
    },
    addAEditDialogClose () {
      this.$refs.addAEditRoleFormRef.resetFields()
    },
    addAEditDialogclick () {
      this.$refs.addAEditRoleFormRef.validate(async valid => {
        if (!valid) return
        if (this.addAEditTitle === 'add') {
          const { data: res } = await this.$http.post('roles', this.addAEditRoleForm)
          if (res.meta.status !== 201) return this.$message.error('添加角色失败！')
          this.$message.success('添加角色成功！')
          this.getRoleList()
        } else if (this.addAEditTitle === 'edit') {
          const { data: res } = await this.$http.put('roles/' + this.editRoleId, { roleName: this.addAEditRoleForm.roleName, roleDesc: this.addAEditRoleForm.roleDesc })
          if (res.meta.status !== 200) return this.$message.error('修改角色失败！')
          this.$message.success('修改角色成功！')
          this.getRoleList()
        }
        this.addAEditDialogVisible = false
      })
    },
    async deleteRole (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message('已取消删除！')
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) this.$message.error('删除角色失败！')
      this.$message.success('删除角色成功！')
      this.getRoleList()
    }
  },
  computed: {
    addAEditDialogTitle () {
      return this.addAEditTitle === 'edit' ? '修改角色' : '添加角色'
    }
  }
}
</script>
<style scoped>
.el-tag {
  margin: 7px;
}
.dbTop {
  border-top: 1px solid #eee;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
</style>
